package com.example.netty.dubborpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yifeng
 */
public class NettyClient {
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static NettyClientHandler client;

    // 使用代理模式，获取一个代理对象
    public Object getBean(final Class<?> seriviceClass, final  String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[] {seriviceClass}, ((proxy, method, args) -> {
                    // {} 部分的代码，客户端每调用一次 hello，就会进入该代码
                    if (client == null) {
                        initClient();
                    }
                    // 设置准备发给服务器的信息
                    // providerName 协议头 args[0]客户端调用 api hello(???) 参数
                    client.setPara(providerName + args[0]);
                    return executor.submit(client).get();
                }));
    }

    // 初始化客户端
    private static void initClient() {
        client = new NettyClientHandler();
        // 创建 EventLoopGroup
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(client);
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.connect("localhost", 7001).sync();
            // 注意，这里不能这么写，会阻塞的，要想监听，再弄一个线程去异步监听好了
//            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            group.shutdownGracefully();
        }
    }
}
